package com.ruoyi.notice.listener;

import com.ruoyi.common.core.utils.DateUtils;
import com.ruoyi.notice.config.RabbitConfig;
import com.ruoyi.notice.config.WsServerEndpont;
import com.ruoyi.notice.domain.Message;
import com.ruoyi.notice.domain.WithdrawalPC;
import com.ruoyi.notice.domain.carNotice;
import com.ruoyi.notice.mapper.TotalAmountMapper;
import com.ruoyi.notice.service.IWithdrawalPCService;
import com.ruoyi.notice.service.MessageService;
import com.ruoyi.notice.service.ShopUserService;
import com.ruoyi.notice.service.UserService;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;

/**
 * @author 23118
 * @version 1.0
 * @description: TODO
 * @date 2025/5/12 14:48
 */
@Component
public class MyListener {
//    @Autowired
//    private RabbitTemplate rabbitTemplate;
    @Autowired
    private MessageService messageService;
    @Autowired
    private UserService userService;
    @Autowired
    private ShopUserService shopUserService;
    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Autowired
    private IWithdrawalPCService withdrawalPCService;
    @Autowired
    private TotalAmountMapper totalAmountMapper;

    //监听删除救援消息队列
    @RabbitListener(queues = RabbitConfig.CAR_DELETE_RESCUE_MESSAGE_QUEUE)
    public void receiveDeleteRescueMessage(Message message) {
        String hid = message.getHid();
        if(hid!=null){
            //根据hid删除救援消息
            messageService.deleteRescueMessageByHid(hid);
            //修改用户的救援消息
            Message message1 = new Message();
            message1.setHid(hid);
            message1.setRead(1L);
            message1.setTitle("救援无人应答");
            message1.setContent("商家正忙，无法为您救援，请稍后再试！");
            messageService.updateMessageByHid(message1);
        }
    }

    //监听提现死信队列
    @RabbitListener(queues = RabbitConfig.CAR_WITHDRAWAL_MESSAGE_DEAD_QUEUE)
    @Transactional
    public void receiveWithdrawalDeadMessage(Map map) {
        //根据提现id(将Integer强转为Long)查询提现信息
        Object idObj = map.get("id");
        Long id;

        if (idObj instanceof Number) {
            id = ((Number) idObj).longValue(); // 自动转换为 long
        } else if (idObj instanceof String) {
            id = Long.parseLong((String) idObj); // 处理字符串类型
        } else {
            // 处理其他类型或抛出异常
            throw new IllegalArgumentException("ID 类型不支持: " + idObj);
        }
        WithdrawalPC withdrawalPC = withdrawalPCService.selectWithdrawalPCById(id);
        //如果提现信息不为空
        if (withdrawalPC != null) {
            Long status = withdrawalPC.getStatus();
            //如果提现状态为1和2
            if (status == 0) {
                //设置提现状态为2
                withdrawalPC.setStatus(2L);
                //修改提现信息
                withdrawalPCService.updateWithdrawalPC(withdrawalPC);
                //返还金额
                totalAmountMapper.updateBalance(Math.toIntExact(withdrawalPC.getMerchantId()), totalAmountMapper.getBalance(withdrawalPC.getMerchantId())+withdrawalPC.getCashWithdrawal());
            }
        }
    }


    //监听全部消息队列
    @RabbitListener(queues = RabbitConfig.CAR_ALL_NOTICE_QUEUE)
    public void receiveMessage(carNotice carNotice) {
//        System.out.println("Received message: " + carNotice);
        //获取所用商家用户的用户id
        List<Long> shopUserIds = getShopUserIds();
        //获取所用用户的用户id
        List<Long> userIds = getUserIds();
        //遍历用户id，向消息中心表中添加数据
        saveUserMessage(carNotice, userIds);
        //遍历商家用户id，向消息中心表中添加数据
        saveShopMessage(carNotice, shopUserIds);
    }
    //监听用户消息队列
    @RabbitListener(queues = RabbitConfig.CAR_USER_NOTICE_QUEUE)
    public void receiveUserMessage(carNotice carNotice) {
        //获取所用用户的用户id
        List<Long> userIds = getUserIds();
        //遍历用户id，向消息中心表中添加数据
        saveUserMessage(carNotice, userIds);
    }
    //监听商家消息队列
    @RabbitListener(queues = RabbitConfig.CAR_SHOP_NOTICE_QUEUE)
    public void receiveShopMessage(carNotice carNotice) {
        //获取所用商家用户的用户id
        List<Long> shopUserIds = getShopUserIds();
        //遍历商家用户id，向消息中心表中添加数据
        saveShopMessage(carNotice, shopUserIds);
    }
    //监听删除消息队列
    @RabbitListener(queues = RabbitConfig.CAR_DELETE_NOTICE_QUEUE)
    public void receiveDeleteMessage(carNotice carNotice) {
        //根据消息id删除消息中心表中的数据
        Long noticeId = carNotice.getNoticeId();
        if(noticeId!=null){
//            System.out.println(noticeId);
            messageService.deleteMessageByNoticeId(noticeId);
        }
    }
    //监听订单消息队列
    @RabbitListener(queues = RabbitConfig.CAR_ORDER_MESSAGE_QUEUE)
    public void receiveOrderMessage(Message message) {
        //设置消息状态为未读
        message.setRead(0L);
        //设置消息状态为未删除
        message.setDel(0L);
        //设置消息时间为当前时间
        message.setTime(DateUtils.getNowDate());
        //向消息中心表中添加一条数据
        messageService.insertMessage(message);
        //发送websocket消息
        WsServerEndpont.sessionMap.forEach((key,value)->{
            try {
                value.getBasicRemote().sendText("您有一条订单消息请注意查收");
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        });
    }
    //监听救援消息队列
    @RabbitListener(queues = RabbitConfig.CAR_RESCUE_MESSAGE_QUEUE)
    public void receiveRescueMessage(Message message) {
        //设置消息状态为未读
        message.setRead(0L);
        //设置消息状态为未删除
        message.setDel(0L);
        //设置消息时间为当前时间
        message.setTime(DateUtils.getNowDate());
        //向当前用户发送一条救援记录消息
        messageService.insertMessage(message);
        //发送延时消息
        rabbitTemplate.convertAndSend(RabbitConfig.CAR_NOTICE_EXCHANGE,"rescueWait",message);
        //将用户id设置为null
        message.setUid(null);
        //向所有商家发送消息
        List<Long> shopUserIds = getShopUserIds();
        for (Long shopUserId : shopUserIds) {
            message.setSid(shopUserId);
            //向消息中心表中添加一条数据
            messageService.insertMessage(message);
        }
    }
    //监听死信消息队列
    @RabbitListener(queues = RabbitConfig.CAR_RESCUE_MESSAGE_DEAD_QUEUE)
    public void receiveDeadMessage(Message message) {
        //分两步，1删除所有商家该条救援消息，2修改该用户的救援状态为无人接收
        //1删除所有商家该条救援消息
//        System.out.println("删除消息");
        messageService.deleteMessageByHid(message.getHid());
        //2修改该用户的救援状态为无人接收
        message.setRead(2L);
        message.setTitle("救援无人应答");
        message.setContent("商家正忙，无法为您救援，请稍后再试！");
//        System.out.println("修改消息");
        messageService.updateMessageByHid(message);
    }
    //添加用户消息
    private void saveUserMessage(carNotice carNotice, List<Long> userIds) {
        // 自定义消息
        Message message = new Message();
        for (Long userId : userIds) {
            message.setUid(userId);
            message.setTitle(carNotice.getNoticeTitle());
            message.setContent(carNotice.getNoticeContent());
            message.setTime(carNotice.getUpdateTime());
            message.setRead(0L);
            message.setDel(0L);
            message.setNoticeid(carNotice.getNoticeId());
            //向消息中心表中添加数据
            messageService.insertMessage(message);
        }
        //发送websocket消息
        WsServerEndpont.sessionMap.forEach((key,value)->{
            try {
                value.getBasicRemote().sendText("您有一条新消息请注意查收");
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        });
    }
    //添加商家消息
    private void saveShopMessage(carNotice carNotice, List<Long> shopUserIds) {
        // 自定义消息
        Message message = new Message();
        for (Long shopUserId : shopUserIds) {
            message.setSid(shopUserId);
            message.setTitle(carNotice.getNoticeTitle());
            message.setContent(carNotice.getNoticeContent());
            message.setTime(carNotice.getUpdateTime());
            message.setRead(0L);
            message.setDel(0L);
            message.setNoticeid(carNotice.getNoticeId());
            //向消息中心表中添加数据
            messageService.insertMessage(message);
        }
    }
    //获取所用商家用户的用户id
    private List<Long> getShopUserIds() {
        //获取所用商家用户的用户id
        List<Long> shopUserIds = shopUserService.selectAllShopUserIds();
        return shopUserIds;
    }
    //获取所用用户的用户id
    private List<Long> getUserIds() {
        //获取所用用户的用户id
        List<Long> userIds = userService.selectAllUserIds();
        return userIds;
    }
}
